
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.http.util.TextUtils;
import ui.ConfigDialog;
import utils.AndroidUtils;

import javax.swing.*;
import java.io.File;
import java.util.*;

public class ConfigModelsOperation extends AnAction {
    private Project mProject;

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 测试代码
        mProject = e.getData(PlatformDataKeys.PROJECT);
        if (mProject != null) {
            VirtualFile file = AndroidUtils.getBuildConfigPath(mProject);
            if (file != null) {
                //获取buildConfig文件夹下的所有环境配置文件名称
                String[] files = AndroidUtils.getBuildConfigFiles(file);
                //过滤到的配置文件中设置的所有组件
                showDialog(files);
            }
        }
    }

    /**
     * 显示UI设置界面
     */
    private void showDialog(String[] configs) {

        ConfigDialog dialog = new ConfigDialog(configs);
        dialog.setOnGenerateListener(new ConfigDialog.OnGenerateListener() {
            @Override
            public void onGenerate(HashMap<String, String> hashMap) {

                //检查输入数据 如果输入数据为空 则提示弹框
                Set<Map.Entry<String, String>> entries = hashMap.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    if (TextUtils.isEmpty(entry.getValue())) {
                        JOptionPane.showMessageDialog(null, "请输入 " + entry.getKey().replace(":", "") + " 的值");
                        return;
                    }
                }

                //检查工程下的asset文件夹目录下是否有配置http私钥se或者pem文件
                if (AndroidUtils.checkFileIsExit(mProject, hashMap.get(ConfigDialog.HTTP_SE))) {
                    JOptionPane.showMessageDialog(null, "请在主工程的asset文件夹下放置 " + hashMap.get(ConfigDialog.HTTP_SE) + " 文件");
                    return;
                }

                //检查工程下的asset文件夹目录下是否有配置mstp私钥se或者pem文件
                if (AndroidUtils.checkFileIsExit(mProject, hashMap.get(ConfigDialog.MSTP_SE))) {
                    JOptionPane.showMessageDialog(null, "请在主工程的asset文件夹下放置 " + hashMap.get(ConfigDialog.MSTP_SE) + " 文件");
                    return;
                }

                //读出选择处理的环境配置文档
                String path = mProject.getBasePath() + File.separator +
                        "buildConfig" + File.separator + hashMap.get(ConfigDialog.CONFIG_FILE);
                //保存读出的文件内容
                ArrayList<String> list = AndroidUtils.readConfigFileSting(mProject, path);

                for (int i = 0; i < list.size(); i++) {
                    String content = list.get(i);
                    if (content.contains(Env_HTTPHost)) {
                        resetContent(hashMap.get(ConfigDialog.HTTP_HOST), list, i, content, false);
                    } else if (content.contains(Env_HTTPPort)) {
                        resetContent(hashMap.get(ConfigDialog.HTTP_PORT), list, i, content, false);
                    } else if (content.contains(Env_HTTP_SeFile)) {
                        resetContent(hashMap.get(ConfigDialog.HTTP_SE), list, i, content, false);
                    } else if (content.contains(Env_HTTP_PublicKey)) {
                        resetContent(hashMap.get(ConfigDialog.HTTP_CPRY), list, i, content, false);
                    } else if (content.contains(Env_MSTPHost)) {
                        resetContent(hashMap.get(ConfigDialog.MSTP_HOST), list, i, content, false);
                    } else if (content.contains(Env_MSTPPort)) {
                        resetContent(hashMap.get(ConfigDialog.MSTP_PORT), list, i, content, false);
                    } else if (content.contains(Env_MSTP_SeFile)) {
                        resetContent(hashMap.get(ConfigDialog.MSTP_SE), list, i, content, false);
                    } else if (content.contains(Env_MSTP_PublicKey)) {
                        resetContent(hashMap.get(ConfigDialog.MSTP_CPRY), list, i, content, false);
                    } else if (content.contains(Env_MSTP_FileServer) || content.contains(Env_MSTP_FileDownloadUrl)) {
                        //mstp的域名和端口配置   mstp网络连接url重置
                        String host = hashMap.get(ConfigDialog.MSTP_HOST);
                        String port = hashMap.get(ConfigDialog.MSTP_PORT);
                        resetContent(host + ":" + port, list, i, content, true);
                    } else if (content.contains(Env_DssHelpUrl) || content.contains(Env_CreateCompanyUrl) ||
                            content.contains(Env_BusinessCardUrl) || content.contains(Env_AddUser_QrCode_Url)
                            || content.contains(App_PrivacyPolicyUrl) || content.contains(App_UserProtocolUrl)) {
                        //http的域名和端口配置   http网络连接url重置   首页连接url端口和域名不做处理
                        String host = hashMap.get(ConfigDialog.HTTP_HOST);
                        String port = hashMap.get(ConfigDialog.HTTP_PORT);
                        resetContent(host + ":" + port, list, i, content, true);
                    } else if (content.contains(App_MainPageConfig)) {
                        //http的域名和端口配置，重置首页url的端口和域名
                        String host = hashMap.get(ConfigDialog.HTTP_HOST);
                        String port = hashMap.get(ConfigDialog.HTTP_PORT);
                        resetMainUrl(host + ":" + port, list, i, content);
                    }
                }
                VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
                StringBuilder builder = new StringBuilder();
                for (String s : list) {
                    builder.append(s).append("\n");
                }
                //处理之后 重新生成文件即可
                assert file != null;
                AndroidUtils.writerFileSting(file, builder.toString());
            }
        });
        dialog.pack();
        dialog.setVisible(true);

    }

    private void resetMainUrl(String setValue, ArrayList<String> list, int i, String content) {
        int index = content.indexOf("http");
        String head = content.substring(0, index);
        String replace = null;
        String[] second = content.substring(index).split("\"");
        if (second.length == 3) {
            replace = second[0].replace(" ", "");
            if (!TextUtils.isEmpty(replace)) {
                String[] split = setValue.split(":");
                String host = split[0];
                String port = split[1];
                setValue = AndroidUtils.replaceHostAndPort(host, port, replace);
            }
            String result = head + setValue + "\"" + second[1] + "\"" + second[2];
            list.set(i, result);
        }
    }

    private void resetContent(String setValue, ArrayList<String> list, int i, String content, boolean isReplace) {
        int index = content.indexOf(":");
        String head = content.substring(0, index);

        String end = null;
        String replace = null;

        String[] second = content.substring(index + 1).split(",");
        if (second.length == 2) {
            end = second[1];
            replace = second[0].replace("\\\"", "");
        }

        if (isReplace && !TextUtils.isEmpty(replace)) {
            String[] split = setValue.split(":");
            String host = split[0];
            String port = split[1];
            setValue = AndroidUtils.replaceHostAndPort(host, port, replace);
        }

        String result = head + ": " + "\\\"" + setValue + "\\\"," + end;
        list.set(i, result);
    }

    private static final String Env_HTTPHost = "\\\"Env_HTTPHost\\\"";
    private static final String Env_HTTPPort = "\\\"Env_HTTPPort\\\"";
    private static final String Env_HTTP_SeFile = "\\\"Env_HTTP_SeFile\\\"";
    private static final String Env_HTTP_PublicKey = "\\\"Env_HTTP_PublicKey\\\"";
    private static final String Env_MSTPHost = "\\\"Env_MSTPHost\\\"";
    private static final String Env_MSTPPort = "\\\"Env_MSTPPort\\\"";
    private static final String Env_MSTP_SeFile = "\\\"Env_MSTP_SeFile\\\"";
    private static final String Env_MSTP_PublicKey = "\\\"Env_MSTP_PublicKey\\\"";

    //替换url里的端口和域名配置
    private static final String Env_MSTP_FileServer = "\\\"Env_MSTP_FileServer\\\"";
    private static final String Env_MSTP_FileDownloadUrl = "\\\"Env_MSTP_FileDownloadUrl\\\"";
    private static final String Env_DssHelpUrl = "\\\"Env_DssHelpUrl\\\"";
    private static final String Env_CreateCompanyUrl = "\\\"Env_CreateCompanyUrl\\\"";
    private static final String Env_BusinessCardUrl = "\\\"Env_BusinessCardUrl\\\"";
    private static final String Env_AddUser_QrCode_Url = "\\\"Env_AddUser_QrCode_Url\\\"";
    private static final String App_PrivacyPolicyUrl = "\\\"App_PrivacyPolicyUrl\\\"";
    private static final String App_UserProtocolUrl = "\\\"App_UserProtocolUrl\\\"";

    //首页url的端口和域名处理
    private static final String App_MainPageConfig = "App_MainPageConfig";


}
